<template>
    <el-dialog :title="titleMap[mode]" v-model="visible" :width="1500"  destroy-on-close @closed="$emit('closed')" align-center>
        <el-button type="primary" @click="print">打印</el-button>
        <el-main class="printMain" ref="printMain">
            <div style="display: flex;justify-content: space-evenly;margin-bottom: 30px">
                <!-- <div class="title"></div> -->
                <div class="title">{{detail.container_code}}货柜码单-{{ware_name}}</div>
                <!-- <div class="title">单位：码</div> -->
            </div>
            <table style="border-collapse: collapse; width: 100%;">
                <thead>
                    <tr style="display: block;margin-top: 10px;border: none;"></tr>
                    <tr style="height:32px;line-height: 32px;">
                        <th class="table_border" colspan="3">{{detail.send_code}}</th>
                        <th class="table_border" colspan="3">车牌号：{{detail.car_code}}</th>
                        <th class="table_border" colspan="3">司机电话：{{detail.car_mobile}}</th>
                    </tr>
                    <tr style="height:32px;line-height: 32px;">
                        <th class="table_border" style="width: 150px">品名</th>
                        <th class="table_border">货号</th>
                        <th class="table_border">花型</th>
                        <th class="table_border">颜色</th>
                        <!-- <th class="table_border">单位</th> -->
                        <th class="table_border">匹数</th>
                        <th class="table_border">总码数</th>
                        <th class="table_border">加工费</th>
                        <th class="table_border">金额</th>
                        <th class="table_border">注</th>
                    </tr>
                </thead>
                <tbody>
                    <!-- 按品名(goods_name)、花型(flower)和颜色(color)分组循环展示数据 -->
                    <template v-for="(goodsGroup, goodsIndex) in order_detail" :key="goodsIndex">
                        <template v-for="(flowerGroup, flowerIndex) in goodsGroup.flowerGroups" :key="flowerIndex">
                            <template v-for="(colorGroup, colorIndex) in flowerGroup.colorGroups" :key="colorIndex">
                                <!-- 每组数据的详细行 -->
                                <tr v-for="(item, itemIndex) in colorGroup.items" :key="itemIndex">
                                    <!-- 品名列 - 合并单元格 -->
                                    <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="flowerIndex === 0 && colorIndex === 0 && itemIndex === 0">
                                        {{goodsGroup.goods_name}}
                                    </td>
                                    <!-- 货号列 - 合并单元格 -->
                                    <td class="table_border" :rowspan="goodsGroup.totalRows" v-if="flowerIndex === 0 && colorIndex === 0 && itemIndex === 0">
                                        {{goodsGroup.goods_code}}
                                    </td>
                                    <!-- 花型列 - 合并单元格 -->
                                    <td class="table_border" :rowspan="flowerGroup.totalRows" v-if="colorIndex === 0 && itemIndex === 0">
                                        {{flowerGroup.flower}}
                                    </td>
                                    <!-- 颜色列 - 合并单元格 -->
                                    <td class="table_border" :rowspan="colorGroup.items.length" v-if="itemIndex === 0">
                                        {{colorGroup.color}}
                                    </td>
                                    <!-- 其他列数据 -->
                                    <!-- <td class="table_border">{{item.unit_name}}</td> -->
                                    <td class="table_border">{{item.number}}</td>
                                    <td class="table_border">{{item.total_number}}</td>
                                    <td class="table_border">{{item.price}}</td>
                                    <td class="table_border">{{item.total_price}}</td>
                                    <td class="table_border">{{item.remark}}</td>
                                </tr>
                            </template>
                        </template>
                        <!-- 品名合计行 -->
                        <tr style="background-color: #dce6f1;">
                            <td class="table_border"></td>
                            <td class="table_border" colspan="3" style="text-align: center; font-weight: bold;">小计</td>
                            <td class="table_border" style="font-weight: bold;">{{goodsGroup.total_count}}</td>
                            <td class="table_border" style="font-weight: bold;">{{goodsGroup.total_number_sum}}</td>
                            <td class="table_border"></td>
                            <td class="table_border" style="font-weight: bold;">{{goodsGroup.total_price_sum}}</td>
                            <td class="table_border"></td>
                        </tr>
                    </template>
                </tbody>
                <!-- 汇总表总合计行 -->
                <tfoot>
                    <tr style="background-color: #b1d0f0; font-weight: bold;">
                        <td class="table_border"></td>
                        <td class="table_border" colspan="3" style="text-align: center;">总计</td>
                        <td class="table_border">{{summaryGrandTotals.total_count}}</td>
                        <td class="table_border">{{summaryGrandTotals.total_number_sum}}</td>
                        <td class="table_border"></td>
                        <td class="table_border">{{summaryGrandTotals.total_price_sum}}</td>
                        <td class="table_border"></td>
                    </tr>
                </tfoot>
            </table>
            
            <!-- 汇总表格：按品名汇总，花型用/合并，数量合计 -->
            <div class="title" style="margin-top: 20px;">汇总表</div>
            <table style="border-collapse: collapse; width: 100%;">
                <thead>
                    <tr style="display: block;margin-top: 10px;border: none;"></tr>
                    <tr style="height:32px;line-height: 32px;">
                        <th class="table_border">品名</th>
                        <th class="table_border">货号</th>
                        <th class="table_border">花型</th>
                        <th class="table_border">单位</th>
                        <th class="table_border">件数</th>
                        <th class="table_border">总数量</th>
                        <th class="table_border">加工费</th>
                        <th class="table_border">金额</th>
                        <th class="table_border">注</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="(summary, index) in summary_detail" :key="index">
                        <td class="table_border">{{summary.goods_name}}</td>
                        <td class="table_border">{{summary.goods_code}}</td>
                        <td class="table_border">{{summary.flowers}}</td>
                        <td class="table_border">{{summary.unit_name}}</td>
                        <td class="table_border">{{summary.total_count}}</td>
                        <td class="table_border">{{summary.total_number_sum}}</td>
                        <!-- <td class="table_border">{{(summary.total_price_sum / summary.total_number_sum).toFixed(2)}}</td> -->
                        <td class="table_border">{{summary.price}}</td>
                        <td class="table_border">{{summary.total_price_sum}}</td>
                        <td class="table_border"></td>
                    </tr>
                </tbody>
                <!-- 总合计行 -->
                <tfoot>
                    <tr style="background-color: #b1d0f0; font-weight: bold;">
                        <td class="table_border" colspan="4" style="text-align: center;">总计</td>
                        <td class="table_border">{{grandTotals.total_count}}</td>
                        <td class="table_border">{{grandTotals.total_number_sum}}</td>
                        <td class="table_border"></td>
                        <td class="table_border">{{grandTotals.total_price_sum}}</td>
                        <td class="table_border"></td>
                    </tr>
                </tfoot>
            </table>
            
        </el-main>
	</el-dialog>
</template>

<script>
import print from '@/utils/print'
export default {
	emits: ['success', 'closed'],
	data() {
        return {
            dialog: {
                client: false
            },
            mode: "add",
            titleMap: {
                print: '打印',
            },
            visible: false,
            detail: {},
            order_detail: [],
            summary_detail: [], // 按品名汇总的数据，花型用/合并，数量合计
            grandTotals: { // 所有品名的总合计
                total_count: 0, // 总匹数
                total_number_sum: 0, // 总总码数
                total_price_sum: 0 // 总金额
            },
            summaryGrandTotals: { // 汇总表的总合计
                total_count: 0, // 总件数
                total_number_sum: 0, // 总总数量
                total_price_sum: 0 // 总金额
            },
            ware_name: "",
        }
    },
	mounted() {
	},
	methods: {
        print(){
            print(this.$refs.printMain)
            setTimeout(()=>{
                this.visible = false
            },500)
        },
		//显示
		open(mode = 'add') {
			this.mode = mode;
			this.visible = true;
			return this
		},
        async setData(data) {
            this.ware_name = data.ware?.ware_name
            var res = await this.$API.ware.ware.applysend.detail.get({id: data.id});
            this.detail = res.data;
            
            // 处理数据
            // 先创建一个临时对象，用于统计相同goods_name、flower和color的数量和合计值
            const uniqueMap = new Map()
            
            // 遍历数据，合并相同goods_name、flower和color的数据
            res.data.detail.forEach(item => {
                const key = `${item?.inspect.goods_name}_${item?.inspect.flower}_${item?.inspect.color_en}`
                
                if (!uniqueMap.has(key)) {
                    // 如果是新的组合，创建新对象
                    uniqueMap.set(key, {
                        goods_id: item?.inspect.goods_id,
                        goods_name: item?.inspect.goods_name,
                        goods_code: item?.inspect.goods_code,
                        flower: item?.inspect.flower,
                        color: item?.inspect.color_en,
                        unit_name: "码",
                        number: 1, // 初始数量为1
                        code_number: Number(item?.inspect?.code_number) || 0,
                        total_number: Number(item?.inspect?.code_number) || 0,
                        total_meter: Number(item?.inspect?.meter) || 0,
                        total_price: (Number(item.process_price)).toFixed(2),
                        price: item.process_price,
                        remark: item.remark,
                    })
                } else {
                    // 如果已存在该组合，累加数量和合计值
                    const existingItem = uniqueMap.get(key)
                    console.log('existingItem :>> ', existingItem);
                    existingItem.number += 1
                    // existingItem.code_number += Number(item?.inspect?.code_number) || 0
                    existingItem.total_number += Number(item?.inspect?.code_number) || 0
                    existingItem.total_meter += Number(item?.inspect?.meter) || 0
                    existingItem.total_price = (Number(existingItem.price) * Number(existingItem.total_meter)).toFixed(2)
                }
            })
            
            // 将Map转换为数组
            let array = Array.from(uniqueMap.values()).map(item => ({
                ...item,
                total_number: (item.total_number).toFixed(2), // 格式化总码数
            }))
            
            // 按goods_name、flower和color分组数据，并计算合计
            this.order_detail = this.groupDataByGoodsAndFlower(array)
            
            // 创建按goods_name汇总的数据，合并花型并用/分隔，合计数量
            this.summary_detail = this.createSummaryData(array)
            
            // 计算所有品名的总合计
            this.calculateGrandTotals(array)
            
            // 计算汇总表的总合计
            this.calculateSummaryGrandTotals()
        },
        
        // 计算所有品名的总合计
        calculateGrandTotals(data) {
            console.log('data :>> ', data);
            let grandTotalCount = 0
            let grandTotalNumber = 0
            let grandTotalPrice = 0
            
            data.forEach(item => {
                grandTotalCount += item.number
                grandTotalNumber += parseFloat(item.total_number)
                grandTotalPrice += parseFloat(item.total_price)
            })
            
            this.grandTotals = {
                total_count: grandTotalCount,
                total_number_sum: grandTotalNumber.toFixed(2),
                total_price_sum: grandTotalPrice.toFixed(2)
            }
        },
        
        // 计算汇总表的总合计
        calculateSummaryGrandTotals() {
            let grandTotalCount = 0
            let grandTotalNumber = 0
            let grandTotalPrice = 0
            
            this.summary_detail.forEach(item => {
                grandTotalCount += item.total_count
                grandTotalNumber += parseFloat(item.total_number_sum)
                grandTotalPrice += parseFloat(item.total_price_sum)
            })
            
            this.summaryGrandTotals = {
                total_count: grandTotalCount,
                total_number_sum: grandTotalNumber.toFixed(2),
                total_price_sum: grandTotalPrice.toFixed(2)
            }
        },
        // 按goods_name、flower和color分组数据
        groupDataByGoodsAndFlower(data) {
            // 创建一个Map来存储每个goods_name的分组
            const goodsMap = new Map();
            
            // 遍历数据，按goods_name、flower和color分组
            data.forEach(item => {
                const goodsName = item.goods_name;
                const flower = item.flower;
                const color = item.color;
                
                // 如果goods_name不存在于Map中，创建新的goods分组
                if (!goodsMap.has(goodsName)) {
                    goodsMap.set(goodsName, {
                        goods_id: item.goods_id,
                        goods_name: goodsName,
                        goods_code: item.goods_code,
                        flowerGroups: [],
                        totalRows: 0, // 该品名的总行数(包括明细和合计行)
                        total_count: 0, // 合计匹数
                        total_number_sum: 0, // 合计总码数
                        total_price_sum: 0 // 合计金额
                    });
                }
                
                const goodsGroup = goodsMap.get(goodsName);
                
                // 查找当前flower的分组
                let flowerGroup = goodsGroup.flowerGroups.find(group => group.flower === flower);
                
                // 如果flower分组不存在，创建新的flower分组
                if (!flowerGroup) {
                    flowerGroup = {
                        flower: flower,
                        colorGroups: [],
                        totalRows: 0 // 该花型的总行数
                    };
                    goodsGroup.flowerGroups.push(flowerGroup);
                }
                
                // 查找当前color的分组
                let colorGroup = flowerGroup.colorGroups.find(group => group.color === color);
                // 如果color分组不存在，创建新的color分组
                if (!colorGroup) {
                    colorGroup = {
                        color: color,
                        items: []
                    };
                    flowerGroup.colorGroups.push(colorGroup);
                }
                
                // 将当前项添加到color分组中
                colorGroup.items.push(item);
                
                // 更新品名的合计值
                goodsGroup.total_count += item.number;
                goodsGroup.total_number_sum += parseFloat(item.total_number);
                goodsGroup.total_price_sum += parseFloat(item.total_price);
            });
            
            // 计算每个goods分组和flower分组的总行数
            const result = Array.from(goodsMap.values());
            result.forEach(goodsGroup => {
                // 计算每个flower分组的总行数
                goodsGroup.flowerGroups.forEach(flowerGroup => {
                    flowerGroup.totalRows = flowerGroup.colorGroups.reduce((total, colorGroup) => total + colorGroup.items.length, 0);
                });
                
                // 计算每个goods分组的总行数
                goodsGroup.totalRows = goodsGroup.flowerGroups.reduce((total, flowerGroup) => total + flowerGroup.totalRows, 0);
                
                // 格式化合计值
                goodsGroup.total_number_sum = (goodsGroup.total_number_sum).toFixed(2);
                goodsGroup.total_price_sum = (goodsGroup.total_price_sum).toFixed(2);
            });
            
            return result;
        },
        
        // 创建按goods_name和price汇总的数组，合并花型并用/分隔，合计数量
        createSummaryData(data) {
            const summaryMap = new Map();
            // 遍历数据，按goods_name和price分组，合并花型并合计数量
            // 这样同品名不同价格的花型会单独分组
            data.forEach(item => {
                // 使用goods_name和price的组合作为Map的键，确保不同价格的同品名单独分组
                const groupKey = `${item.goods_name}_${item.price}`;
                
                if (!summaryMap.has(groupKey)) {
                    summaryMap.set(groupKey, {
                        goods_id: item.goods_id,
                        goods_name: item.goods_name,
                        goods_code: item.goods_code,
                        price: item.price,
                        flowers: new Set(), // 使用Set存储唯一的花型
                        total_count: 0, // 合计件数
                        total_number_sum: 0, // 合计总数量
                        total_price_sum: 0, // 合计金额
                        unit_name: item.unit_name
                    });
                }
                
                const summary = summaryMap.get(groupKey);
                summary.flowers.add(item.flower); // 添加花型到Set中
                summary.total_count += item.number;
                summary.total_number_sum += parseFloat(item.total_number);
                summary.total_price_sum += parseFloat(item.total_price);
            });
            
            // 转换为数组，处理花型合并和格式化数值
            const result = Array.from(summaryMap.values()).map(item => ({
                ...item,
                flowers: Array.from(item.flowers).join('/'), // 用/分隔合并花型
                total_number_sum: (item.total_number_sum).toFixed(2),
                total_price_sum: (item.total_price_sum).toFixed(2)
            }));
            
            return result;
        },
	}
}
</script>

<style lang="scss">
.title {
    font-size: 20px;
    text-align: center;
    font-weight: bold;
    margin-bottom: 10px;
}
td{
    text-align: center;
}
.table_border{
    width: 80px;
    height: 32px;
    border: 1px solid #000;
}
table{
    tbody{
        font-size: 13px;
        tr {
            page-break-inside: avoid;
            -webkit-region-break-inside: avoid; 
        }
        tr:last-child{
            page-break-after: avoid;
            
        }
    }
} 
</style>
